<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>基础信息</span>
                            <el-button type="primary" icon="el-icon-key"
                                @click="dialogPwdVisible = !dialogPwdVisible">修改密码</el-button>
                        </div>
                    </template>
                    <div class="info">
                        <div class="info-image" @click="showDialog">
                            <img :src="avatarImg" />
                            <span class="info-edit">
                                <i class="el-icon-lx-camerafill"></i>
                            </span>
                        </div>
                        <el-divider/>
                        <el-card shadow="hover" v-show="showPlayerForm">
                            <el-form :model="personInfo" :rules="rules" label-position="right" label-width="100px">
                                <el-form-item label="选手编号">
                                    <el-input v-model="personInfo.playerId" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="姓名" prop="name">
                                    <el-input v-model="personInfo.name" :disabled="hasInfo" placeholder="请输入姓名" clearable></el-input>
                                </el-form-item>
                                <el-form-item label="性别">
                                    <el-input v-model="sex" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="年龄">
                                    <el-input v-model="age" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="身份证号" prop="IDnum">
                                    <el-input v-model="personInfo.IDnum" :disabled="hasInfo" placeholder="请输入身份证号" clearable></el-input>
                                </el-form-item>
                                <el-form-item label="手机号">
                                    <el-input v-model="personInfo.phone" disabled placeholder="请输入手机号"></el-input>
                                </el-form-item>
                                <el-form-item label="学校" prop="school">
                                    <el-input v-model="personInfo.school" placeholder="请输入学校" clearable></el-input>
                                </el-form-item>
                            </el-form>
                            <el-button type="danger" @click="updateInfo" icon="el-icon-refresh">更新</el-button>
                        </el-card>
                        <el-card shadow="hover" v-show="!showPlayerForm">
                            <el-form :model="notPlayer" label-position="right" label-width="100px">
                                <el-form-item label="用户名">
                                    <el-input v-model="notPlayer.username" disabled/>
                                </el-form-item>
                                <el-form-item label="身份">
                                    <el-input v-model="notPlayer.identity" disabled/>
                                </el-form-item>
                                <el-form-item label="手机号">
                                    <el-input v-model="notPlayer.phone" disabled/>
                                </el-form-item>
                            </el-form>
                        </el-card>
                    </div>
                </el-card>
            </el-col>
        </el-row>
       
        <el-dialog title="密码修改" v-model="dialogPwdVisible"  width="400px" center>
            <el-card shadow="hover">
                <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" status-icon
                    label-position="right" label-width="100px">
                <el-form-item label="旧密码" prop="old">
                    <el-input type="password" v-model="pwdForm.old" placeholder="请输入新密码" 
                        show-password clearable ></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="new">
                    <el-input type="password" v-model="pwdForm.new" placeholder="请输入新密码" 
                    show-password clearable></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPwd">
                    <el-input type="password" v-model="pwdForm.confirmPwd" placeholder="请输入确认密码" 
                    show-password clearable></el-input>
                </el-form-item>
            </el-form>
            </el-card>
            <template #footer>
                <el-button @click="dialogPwdVisible = !dialogPwdVisible">取 消</el-button>
                <el-button type="danger" @click="updatePwd">更新</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { computed, onMounted, reactive, ref } from "vue";
import "cropperjs/dist/cropper.css";
import avatar from "../assets/img/default.jpg";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';
import secret from "../utils/secret";
export default {
    setup() {
        const store = useStore();
        const router = useRouter();
        const dialogPwdVisible = ref(false);
        const showPlayerForm = ref(false);
        //非运动员信息
        const notPlayer = reactive({
            username:'',
            phone:'',
            identity:''
        })
        onMounted(()=>{
            getPersonInfo();
            store.dispatch("CurrentUserInfo").then((res) => {
                if (res.code === 200) {
                    // console.log("@@@@@@",res);
                    notPlayer.username = res.obj.username;
                    notPlayer.phone = res.obj.phoneNum;
                    notPlayer.identity = res.obj.roles[0].nameZh;
                    personInfo.phone = res.obj.phoneNum;
                    if(res.obj.authorities[0].authority==="ROLE_Athletes"){
                        showPlayerForm.value = true;
                    }
                } else {
                    console.log(res.message);
                }
            });
        })
        const pwdFormRef = ref()
        const pwdForm = reactive({
            old: "",
            new: "",
            confirmPwd:''
        });
        const pwdRules = {
            old: [
                { required: true, message: "请输入旧密码", trigger: "blur" },
            ],
            new: [
                { required: true, message: "请输入密码", trigger: "blur" },
                { pattern:/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/,
                  message:'长度至少为8，至少含有一个字母和一个数字',
                  trigger: "blur" },
            ],
            confirmPwd: [
                { required: true, message: "请输入确认密码", trigger: "blur" },
                {
                    validator: (rule, value, callback) => {
                        if (value !== pwdForm.new) {
                            callback(new Error("两次输入的密码不一致"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "blur"
                },
            ],
        };
        const updatePwd = ()=>{
            pwdFormRef.value.validate(valid=>{
                if(valid){
                    store.dispatch("VerifyPassword",secret.Encrypt( pwdForm.old))
                    .then(res=>{
                        if(res.code===200){
                            store.dispatch("UpdatePassword",secret.Encrypt(pwdForm.new))
                            .then(res2=>{
                                if(res2.code===200){
                                    ElMessage({
                                        message: "密码修改成功，请重新登录",
                                        type: "success",
                                        center:true
                                    });
                                    dialogPwdVisible.value = false;
                                    store.dispatch("Logout")
                                    .then((res)=>{
                                        if(res.code == 200){
                                            store.commit("clear");
                                            router.push("/login");
                                        }else{
                                            ElMessage({
                                                message: "注销失败 ,"+res.message,
                                                type: "error",
                                                center: true,
                                                duration:1500,
                                            });
                                        }
                                    })
                                }else{
                                    ElMessage({
                                        type: "error",
                                        message: res2.message,
                                        center:true
                                    })
                                }
                            }).catch(err=>{
                                console.log(err);
                            })
                        }else{
                            ElMessage({
                                type: "error",
                                message: res.message,
                                center:true
                            })
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }else{
                    ElMessageBox({
                        title: "提示",
                        message: "请检查表单填写是否规范",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        center:true
                    })
                }
            })
            
        }
       
        /**
         * 个人信息
         */
        const profileFormVisiable = ref(true);
        const personInfo = reactive({
            playerId:'',
            name:"",//姓名
            IDnum:"",//身份证号
            school:"",//学校
            phone:"",//手机号
        })
        const sex = computed(()=>{//0男 1女
            if(personInfo.IDnum.length===18)
                return personInfo.IDnum[16]&1?'男':'女';
            return '';
        })
        const age = computed(()=>{
            if(personInfo.IDnum.length!=18)
                return '';
            let birthYear = personInfo.IDnum.substring(6,10);
            let birthMonth = personInfo.IDnum.substring(10,12);
            let birthDay = personInfo.IDnum.substring(12,14);
            let date = new Date();
            let curAge = date.getFullYear()-birthYear;
            let curMonth = date.getMonth()+1;
            let curDay = date.getDay();
            if(curMonth < birthMonth || (curMonth===birthMonth && curDay < birthDay)){
                curAge--;
            }
            return curAge;
        })
        const rules = {
            name: [
                {required:true,message:'姓名不能为空'},
                {pattern:/^[\u4e00-\u9fa5]{2,9}$/,message:'不符合姓名规则'}
            ],
            IDnum:[
              { required:true,message:'身份证号不能为空'},
              { pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                message:'不符合身份证规则'}
            ],
            school:[
                {required:true,message:'学校不能为空'},
            ]
        }
        const updateInfo = () => {
            if(hasInfo.value){
                store.dispatch("UpdateUserInfo",personInfo.school).then(res=>{
                    if(res.code===200){
                        ElMessage({
                            message: "修改成功",
                            type: "success",
                            center:true
                        });
                    }else{
                        ElMessage({
                            type: "error",
                            message: res.msg,
                            center:true
                        })
                    }
                }).catch(err=>{
                    console.log("更新选手学校异常",err);
                })
                return ;
            }else{
                store.dispatch("PlayerInfoUpdate",{
                    name:personInfo.name,
                    id_Number:personInfo.IDnum,
                    school:personInfo.school,
                    telephone:personInfo.phone,
                    age:age.value,
                    sex:sex.value=='男'?0:1,
                }).then(res=>{
                    if(res==="ok"){
                        ElMessage({
                            type:"success",
                            message:"更新成功",
                            center:true,
                        })
                    }else{
                        ElMessage({
                            type:"error",
                            message:"更新失败, "+res,
                            center:true,
                        })
                    }
                }).catch((err)=>{
                    console.log("更新个人信息异常 ",err);
                })
            }
            
        };

        const hasInfo = ref(true);
        const getPersonInfo = ()=>{
            store.dispatch("GetUserInfo").then(res=>{
                console.log("获取选手个人信息",res);
                if(res.code===200){
                    hasInfo.value = true;
                    personInfo.playerId = res.obj.pid;
                    personInfo.name = res.obj.name;
                    personInfo.IDnum = res.obj.id_Number;
                    personInfo.school = res.obj.school;
                    personInfo.phone = res.obj.telephone;
                }else{
                    console.log("获取个人信息失败");
                    hasInfo.value = false;
                }
            }).catch(err=>{
                console.log("选手查询个人信息异常",err);
            })
        }

        /*头像处理 */
        const avatarImg = ref(avatar);
        

        return {
            pwdForm,
            hasInfo,
            notPlayer,
            showPlayerForm,
            updatePwd,
            pwdFormRef,
            pwdRules,
            profileFormVisiable,
            personInfo,
            sex,
            age,
            rules,
            updateInfo,
            dialogPwdVisible,
            avatarImg,
        };
    },
};
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info {
    text-align: center;
    padding: 35px 0;
}
.info-image {
    position: relative;
    margin: auto;
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 50px;
    overflow: hidden;
}
.info-image img {
    width: 100%;
    height: 100%;
}
.info-edit {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s ease;
}
.info-edit i {
    color: #eee;
    font-size: 25px;
}
.info-image:hover .info-edit {
    opacity: 1;
}
.crop-demo-btn {
    position: relative;
}
.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}
</style>